package com.jyg.common.utils;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;


public class FastDFS {
    public static String FAST_DFS_URL = "http://fastdfs.jayden.ltd";
    private static TrackerServer trackerServer = null;
    private static StorageServer storageServer = null;

    public static StorageClient getStorageClient() throws IOException, MyException {
        //1.加载配置文件，默认去classpath下加载
        ClientGlobal.init("fdfs_client.conf");
        //2.创建TrackerClient对象
        TrackerClient trackerClient = new TrackerClient();
        //3.创建TrackerServer对象
        trackerServer = trackerClient.getConnection();
        //4.创建StorageServler对象
        storageServer = trackerClient.getStoreStorage(trackerServer);
        //5.创建StorageClient对象，这个对象完成对文件的操作
        return new StorageClient(trackerServer, storageServer);
    }

    public static void closeFastDFS() {
        if (storageServer != null) {
            try {
                storageServer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (trackerServer != null) {
            try {
                trackerServer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 上传文件的方法
     */
    public static void fileUpload() {
        try {
            //1. 获取StorageClient对象
            StorageClient storageClient = getStorageClient();
            //2.上传文件  第一个参数：本地文件路径 第二个参数：上传文件的后缀 第三个参数：文件信息
            String[] uploadArray = storageClient.upload_file("D:/My Documents/Pictures/29_785_71a161d6d05edb652d007abdd7554223_f5749f54cb48aa496e43d9ccf337c513.png" , "png" , null);
            for (String str : uploadArray) {
                System.out.println(str);
            }
        } catch (IOException | MyException e) {
            e.printStackTrace();
        } finally {
            closeFastDFS();
        }
    }

    public static String fileUpload(String local_filename, String file_ext_name) {
        try {
            //1. 获取StorageClient对象
            StorageClient storageClient = getStorageClient();
            //2.上传文件  第一个参数：本地文件路径 第二个参数：上传文件的后缀 第三个参数：文件信息
            String[] uploadArray = storageClient.upload_file(local_filename, file_ext_name, null);
            StringBuilder url = new StringBuilder("http://");
            url.append(ClientGlobal.g_tracker_group.tracker_servers[0].getHostName());
            for (String str : uploadArray) {
                url.append("/").append(str);
            }
            return url.toString();
        } catch (IOException | MyException e) {
            e.printStackTrace();
        } finally {
            closeFastDFS();
        }
        return null;
    }

    /**
     * 上传文件的方法
     */
    public static String fileUpload(MultipartFile file) {
        try {
            String type = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            return fileUploadByte(file.getBytes(), type);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        } finally {
            closeFastDFS();
        }
        return null;
    }

    public static String fileUpload(byte[] file, String type) {
        try {
            return fileUploadByte(file, type);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        } finally {
            closeFastDFS();
        }
        return null;
    }

    public static String fileUploadByte(byte[] file, String type) throws IOException, MyException {
        if (ObjectUtil.isEmpty(type)) {
            type = "jpg";
        }
        //1. 获取StorageClient对象
        StorageClient storageClient = getStorageClient();
        //2.上传文件  第一个参数：本地文件路径 第二个参数：上传文件的后缀 第三个参数：文件信息
        String[] uploadArray = storageClient.upload_file(file, type, null);

//        StringBuilder url = new StringBuilder("http://");
//        url.append(ClientGlobal.g_tracker_group.tracker_servers[0].getHostName());
        StringBuilder url = new StringBuilder(FAST_DFS_URL);
        for (String str : uploadArray) {
            url.append("/").append(str);
        }
        return url.toString();
    }

    /**
     * 下载文件的方法
     */
    public static void fileDownload(String groupName, String remoteFilename, String localFilename) {
        try {
            //1. 获取StorageClient对象
            StorageClient storageClient = getStorageClient();
            //2.下载文件 返回0表示成功，其它均表示失败
            int num = storageClient.download_file(groupName, remoteFilename, localFilename);
            System.out.println(num);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        } finally {
            closeFastDFS();
        }
    }


    /**
     * 删除文件的方法
     */
    public static void fileDelete(String groupName, String remoteFilename) {
        try {
            //1. 获取StorageClient对象
            StorageClient storageClient = getStorageClient();
            //2.删除文件 返回0表示成功，其它均表示失败
            int num = storageClient.delete_file(groupName, remoteFilename);
            System.out.println(num);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        } finally {
            closeFastDFS();
        }
    }

    public static String uploadBase64(String base64) {
        String type = "jpg";
        if (base64.contains(",")) {
            if (base64.contains(";") && base64.contains("/")) {
                type = base64.substring(base64.indexOf("/") + 1, base64.indexOf(";"));
            }
            base64 = base64.substring(base64.indexOf(",") + 1);
        }
        try {
            return fileUploadByte(Base64.decode(base64), type);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        }
        return null;
    }

}
